﻿using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Options;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.ComponentModel.DataAnnotations;
using System.Security.Claims;
using System.Threading.Tasks;
using Volo.Abp.Account.Web;
using Volo.Abp.Account.Web.Pages.Account;
using Volo.Abp.AspNetCore.Mvc.UI.RazorPages;
using Volo.Abp.Data;
using Volo.Abp.DependencyInjection;
using Volo.Abp.Identity;
using Volo.Abp.Security.Claims;
using YaAppoint.Users;

namespace YaAppoint.Web.Pages.Account
{
    [ExposeServices(typeof(MyLoginModel))]
    public partial class MyLoginModel :AbpPageModel
    {

        [BindProperty]
        [DisplayName("科室")]
        public string? Department { get; set; }

        [BindProperty]
        [DisplayName("记住我")]
        public bool RememberMe { get; set; }

        [Required(ErrorMessage = "用户名不能为空")]
        [BindProperty]
        [DisplayName("用户名")]
        public string UserName { get; set; }

        [Required(ErrorMessage ="请输入密码")]
        [BindProperty]
        [DisplayName("密码")]
        public string Password { get; set; }

        private readonly UserManager<Volo.Abp.Identity.IdentityUser> _userManager;
        private readonly SignInManager<Volo.Abp.Identity.IdentityUser> _signInManager;
        private readonly ICurrentUserDepartmentAppService _currentUserDepartment;

        public MyLoginModel(
            //IAuthenticationSchemeProvider schemeProvider,
            //IOptions<AbpAccountOptions> accountOptions,
            //IOptions<IdentityOptions> identityOptions,
            ICurrentUserDepartmentAppService currentUserDepartment,
            IdentityDynamicClaimsPrincipalContributorCache identityDynamicClaimsPrincipalContributorCache,
            UserManager<Volo.Abp.Identity.IdentityUser> userManager,
            SignInManager<Volo.Abp.Identity.IdentityUser> signInManager):base()
        {
            _userManager = userManager;
            _signInManager = signInManager;
            _currentUserDepartment= currentUserDepartment;
        }
        public  async Task<IActionResult> OnPostAsync(string returnUrl = null)
        {
            
            if (ModelState.IsValid)
            {
                var user = await _userManager.FindByNameAsync(UserName);
                if (user != null)
                {
                    // 用户科室列表
                    var departmentList = await _currentUserDepartment.GetDepartmentsByUserNameAsync(UserName);

                    if (departmentList != null && departmentList.Count > 0 && !string.IsNullOrEmpty(Department))
                    {
                        if ( await SignInAsync(user))
                        {
                            return LocalRedirect(returnUrl ?? Url.Content("~/"));
                        }
                    }
                    else if (departmentList != null && departmentList.Count > 0 && string.IsNullOrEmpty(Department))
                    {
                        ModelState.AddModelError(nameof(Department), "请选择科室");
                    }
                    else if (departmentList == null || departmentList.Count == 0)
                    {
                        // 是否拥有系统管理员角色
                        var inAdmin = await _userManager.IsInRoleAsync(user, "admin");

                        if (inAdmin)
                        {
                            if (await SignInAsync(user))
                            {
                                return LocalRedirect(returnUrl ?? Url.Content("~/"));
                            }
                        }
                        else
                        {
                            ModelState.AddModelError(nameof(Department),"当前用户还未加入任何科室");
                        }
                    }
                }
                else
                {
                    ModelState.AddModelError("", "用户不存在");
                }
            }

            return Page();
        }

        private async Task<bool> SignInAsync(Volo.Abp.Identity.IdentityUser user)
        {
            bool res = false;

            if (!user.IsActive)
            {
                ModelState.AddModelError("", "用户已被禁用");
            }
            // 验证密码
            var passwordValid = await _userManager.CheckPasswordAsync(user, Password);
            if (passwordValid)
            {
                var claims = new List<Claim>();
                claims.Add(new Claim(AbpClaimTypes.Name, user.Name));
                var jobNumber = user.GetProperty<string>("JobNumber");
                if (!string.IsNullOrEmpty(jobNumber))
                {
                    claims.Add(new Claim("job-number", jobNumber));
                }
                if (!string.IsNullOrEmpty(Department))
                {
                    var args = Department.Split('@');
                    if (args.Length > 0)
                    {
                        claims.Add(new Claim("department-name", args[0]));
                        claims.Add(new Claim("department-id", args[1]));
                    }
                }
               
                var authProps = new AuthenticationProperties
                {
                    IsPersistent = RememberMe,
                    ExpiresUtc = DateTimeOffset.UtcNow.AddHours(24)
                };

                if (RememberMe)
                {
                    authProps.ExpiresUtc = DateTimeOffset.UtcNow.AddDays(15);
                }
                await _signInManager.SignInWithClaimsAsync(user, authProps, additionalClaims: claims);
                res = true;
            }
            else
            {
                ModelState.AddModelError(nameof(UserName), "密码不正确");
            }
            return res;
        }
    }

}


